/*
 * Copyright (C) 2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

using Mono.Unix;
using Gtk;

using DCSharp.Backend.Managers;
using DCSharp.Backend.Objects;
using DCSharp.Hashing;
using DCSharp.Settings;
using DCSharp.Security.Cryptography;

using Timer = System.Timers.Timer;

namespace DCSharp.Gui
{
	public static class Globals
	{
		private const int SaveInterval = 10000;

		private static Runtime runtime;
		private static RuntimeSettings settings;
		private static HashStore hashStore;
		private static QueueLoader queueLoader;

		private static FavoriteManager favoriteManager;
		private static FileFinder finder;

		private static Timer timer;
		private static bool downloadsChanged;
		private static int fileCount;
		private static int hashTreeCount;

		private static Gui gui;
		private static InterfaceSettings interfaceSettings;
		private static Notifications notifications;

		private static string appData;
		private static string tempPath;

		private static string settingsFile;
		private static string interfaceSettingsFile;
		private static string favoritesFile;
		private static string queueFile;

		private static string hashIndexFile;
		private static string hashDataFile;

		static Globals()
		{
			appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
			appData = Path.Combine(appData, "dcsharp");

			tempPath = Path.GetTempPath();
			if (String.IsNullOrEmpty(tempPath))
			{
				tempPath = appData;
			}

			settingsFile = Path.Combine(appData, "Settings.xml");
			interfaceSettingsFile = Path.Combine(appData, "InterfaceSettings.xml");
			favoritesFile = Path.Combine(appData, "Favorites.xml");
			queueFile = Path.Combine(appData, "Queue.xml");

			hashIndexFile = Path.Combine(appData, "HashIndex.xml");
			hashDataFile = Path.Combine(appData, "HashData.dat");

			if (!Directory.Exists(appData))
			{
				Directory.CreateDirectory(appData);
			}
		}

		#region Properties

		public static string ApplicationData
		{
			get { return appData; }
		}

		public static string TempPath
		{
			get { return tempPath; }
		}

		public static Runtime Runtime
		{
			get { return runtime; }
		}

		public static FavoriteManager FavoriteManager
		{
			get { return favoriteManager; }
		}

		public static FileFinder FileFinder
		{
			get { return finder; }
		}

		public static Gui Gui
		{
			get { return gui; }
		}

		public static bool CanShowNotifications
		{
			get { return notifications != null; }
		}

		#endregion

		#region Methods

		public static void Init()
		{
			settings = RuntimeSettings.Load(settingsFile);

			// Initialize
			hashStore = new HashStore(Tiger.Create(), hashIndexFile, hashDataFile);
			runtime = new Runtime(settings, settings.ConnectionSettings,
				hashStore, tempPath, settings.SharedDirectories);

			queueLoader = new QueueLoader(hashStore);
			favoriteManager = FavoriteManager.Load(favoritesFile);
			finder = new FileFinder(runtime);

			interfaceSettings = InterfaceSettings.Load(interfaceSettingsFile);
			gui = new Gui(runtime, settings, interfaceSettings);

			timer = new Timer(SaveInterval);
			timer.Elapsed += OnTimerElapsed;
			timer.Start();

#if ENABLE_NOTIFICATIONS
			try
			{
				notifications = new Notifications(runtime, gui,
					interfaceSettings.NotificationSettings);
			}
			catch
			{
				Console.Error.WriteLine("{0}. {1}",
					Catalog.GetString("Can not show notifications"),
					Catalog.GetString("You need the notification daemon installed for notifications to show."));
			}
#endif
			// Start
			runtime.StartServers();
			ConnectToFavoriteHubs();

			ThreadPool.QueueUserWorkItem(Load);

			// Events
			runtime.DownloadManager.DownloaderAdded += OnDownloadersChanged;
			runtime.DownloadManager.DownloaderRemoved += OnDownloadersChanged;
		}

		public static void Shutdown()
		{
			runtime.DownloadManager.DownloaderAdded -= OnDownloadersChanged;
			runtime.DownloadManager.DownloaderRemoved -= OnDownloadersChanged;
			timer.Stop();
			finder.Dispose();

			TrySaveAll();
			runtime.Shutdown();
		}

		public static void ConnectToFavoriteHubs()
		{
			foreach (FavoriteHubInfo hub in favoriteManager.Hubs)
			{
				if (hub.AutoConnect)
				{
					runtime.ConnectToHub(hub);
				}
			}
		}

		public static void SaveSettings()
		{
			lock (runtime.ShareManager.SyncRoot)
			{
				settings.SharedDirectories = new List<ShareInfo>(runtime.ShareManager);
			}
			lock (settings)
			{
				interfaceSettings.Save(interfaceSettingsFile);
				settings.Save(settingsFile);
			}
		}

		public static void SaveApplicationData(bool force)
		{
			if (force || fileCount != hashStore.FileCount ||
				hashTreeCount != hashStore.HashTreeCount)
			{
				lock (hashStore)
				{
					hashStore.Save();
				}
				fileCount = hashStore.FileCount;
				hashTreeCount = hashStore.HashTreeCount;
			}
			if (force || downloadsChanged)
			{
				lock (runtime.DownloadManager.SyncRoot)
				{
					queueLoader.Save(runtime.DownloadManager, queueFile);
				}
				downloadsChanged = false;
			}
			lock (favoriteManager.SyncRoot)
			{
				favoriteManager.Save(favoritesFile);
			}
		}

		private static void Load(object state)
		{
			// FIXME: The hash store needs to be loaded before creating the ShareManager.
			Try(null, "Could not load the hash store.", delegate
			{
				lock (hashStore)
				{
					if (File.Exists(hashIndexFile) && File.Exists(hashDataFile))
					{
						hashStore.Load();

						fileCount = hashStore.FileCount;
						hashTreeCount = hashStore.HashTreeCount;
					}
				}
			});
			// A hack to for the above issue.
			runtime.ShareManager.Refresh();

			Try(null, "Could not load the download queue.", delegate
			{
				if (File.Exists(queueFile))
				{
					foreach (FileDownloader downloader in queueLoader.Load(queueFile))
					{
						Start(downloader);
					}
				}
			});

			// Get the local IP-address
			if (String.IsNullOrEmpty(settings.ConnectionSettings.Address))
			{
				settings.ConnectionSettings.Address = Util.GetLocalIPAddress();
			}
		}

		private static void Start(FileDownloader downloader)
		{
			string path = Path.Combine(downloader.SavePath, downloader.RemoteFile.Name);
			if (!File.Exists(path))
			{
				runtime.DownloadManager.Add(downloader);
				downloader.SegmentStrategy = runtime.DownloadManager.DefaultSegmentStrategy;
				downloader.Start();
			}
		}

		private static void OnDownloadersChanged(object obj, EventArgs args)
		{
			downloadsChanged = true;
		}

		private static void OnTimerElapsed(object obj, EventArgs args)
		{
			if (downloadsChanged || fileCount != hashStore.FileCount ||
				hashTreeCount != hashStore.HashTreeCount)
			{
				timer.Stop();
				TrySaveAll();
				timer.Start();
			}
		}

		private static void TrySaveAll()
		{
			try
			{
				SaveSettings();
				SaveApplicationData(false);
			}
			catch (Exception e)
			{
				Gui.InvokeAndWait(e, EventArgs.Empty, ShowError);
			}
		}

		private static void ShowError(object obj, EventArgs args)
		{
			Exception e = (Exception)obj;
			MessageDialog dialog = new MessageDialog(
				Catalog.GetString("Could not save the application data"),
				Catalog.GetString("Any changes will be lost unless the data has been saved."),
				e.ToString(), MessageType.Error, Gui.MainWindow);

			dialog.AddButton(Catalog.GetString("_Retry"), ResponseType.Accept);
			dialog.AddButton(Stock.Ok, ResponseType.Ok);			
			dialog.Show();

			ResponseType response = (ResponseType)dialog.Run();
			dialog.Destroy();

			if (response == ResponseType.Accept)
			{
				TrySaveAll();
			}
		}

		private static void Try(string action, string error, EventHandler handler)
		{
			try
			{
				if (action != null)
				{
					Console.WriteLine(action);
				}
				handler(null, EventArgs.Empty);
			}
			catch (Exception e)
			{
				Console.Error.WriteLine("{0}{1}{2}", error, Environment.NewLine, e);
			}
		}

		#endregion
	}
}
